"""认证路由模块"""
from flask import Blueprint, render_template, request, redirect, url_for, session, jsonify
from werkzeug.security import check_password_hash
from app.database import get_db_connection
from app.utils.decorators import login_required

bp = Blueprint('auth', __name__)

@bp.route('/login')
def login_page():
    """登录页面"""
    return render_template('login.html')

@bp.route('/login', methods=['POST'])
def login():
    """登录处理"""
    username = request.form.get('username', '')
    password = request.form.get('password', '')
    
    connection = None
    cursor = None
    
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        
        cursor.execute(
            "SELECT id, username, password_hash FROM users WHERE username = %s",
            (username,)
        )
        user = cursor.fetchone()
        
        if user and check_password_hash(user['password_hash'], password):
            session['username'] = user['username']
            session['user_id'] = user['id']
            return jsonify({'success': True, 'message': '登录成功'})
        else:
            return jsonify({'success': False, 'message': '用户名或密码错误'})
    except Exception as e:
        return jsonify({'success': False, 'message': f'登录过程中发生错误: {str(e)}'})
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()

@bp.route('/logout')
@login_required
def logout():
    """登出"""
    session.clear()
    return redirect(url_for('auth.login_page'))

@bp.route('/change_password', methods=['POST'])
@login_required
def change_password():
    """修改密码"""
    from werkzeug.security import generate_password_hash
    
    old_password = request.form.get('old_password', '')
    new_password = request.form.get('new_password', '')
    
    connection = None
    cursor = None
    
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        
        user_id = session.get('user_id')
        cursor.execute("SELECT password_hash FROM users WHERE id = %s", (user_id,))
        user = cursor.fetchone()
        
        if not user:
            return jsonify({'success': False, 'message': '用户不存在'})
        
        if not check_password_hash(user['password_hash'], old_password):
            return jsonify({'success': False, 'message': '原密码错误'})
        
        if len(new_password) < 4:
            return jsonify({'success': False, 'message': '新密码长度不能少于4位'})
        
        if old_password == new_password:
            return jsonify({'success': False, 'message': '原密码和新密码不能相同'})
        
        new_password_hash = generate_password_hash(new_password)
        cursor.execute("UPDATE users SET password_hash = %s WHERE id = %s", (new_password_hash, user_id))
        connection.commit()
        
        return jsonify({'success': True, 'message': '密码修改成功'})
    except Exception as e:
        if connection:
            connection.rollback()
        return jsonify({'success': False, 'message': f'密码修改失败: {str(e)}'})
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()

